package com.yiren.dbaa.module.common.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.constant.G;
import com.yiren.dbaa.constant.SendParamConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.currency.dialog.CommonDialog;
import com.yiren.dbaa.module.common.bean.LoginQrcodeBean;
import com.yiren.dbaa.module.common.bean.UserConfigBean;
import com.yiren.dbaa.module.common.contract.MainContract;
import com.yiren.dbaa.module.common.contract.RiskControlContract;
import com.yiren.dbaa.module.common.model.MainModel;
import com.yiren.dbaa.module.common.model.RiskControlModel;
import com.yiren.dbaa.module.device.contract.DeviceConnectContract;
import com.yiren.dbaa.module.device.model.DeviceConnectModel;
import com.yiren.dbaa.module.exam.view.activity.ExamDjActivity;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * @author lwb
 * @date : 2022/7/4 11:45
 * @description: 首页P
 */
public class MainPresenter implements MainContract.Presenter {

    private Activity activity;
    private MainContract.Model mainModel;
    private RiskControlContract.Model riskControlModel;
    private Handler taskGpsHandle;
    private DeviceConnectContract.Model deviceConnectModel;

    public MainPresenter(Activity activity) {
        this.activity = activity;
        mainModel = new MainModel(activity);
        riskControlModel = new RiskControlModel(activity);
        deviceConnectModel = new DeviceConnectModel(activity);
        taskGpsHandle = new Handler();
    }

    @Override
    public void getDeviceNumber(MainContract.View view) {
        mainModel.getSimCardInfo(new CommonCallBack() {
            @Override
            public void success(Object result) {
                view.showEquipmentIdState((String) result);
            }
        });
    }

    @Override
    public void prepareExam(String examModel, MainContract.View v) {
        if (null == G.connectDeviceMessage) {
            CommonDialog.showTwoBtn(activity, "设备连接", "设备连接失败，确认重连？", "取消", "重连", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == -2) {

                    } else {
                        deviceConnectModel.startSerialConnect(new CommonCallBack() {
                            @Override
                            public void success(Object result) {
                                deviceConnectModel.connectDevice(new DeviceConnectContract.DeviceConnectCallback() {
                                    @Override
                                    public void onDeviceConnectSuccess() {
                                        MessageBox.show(activity,"设备连接成功");
                                    }

                                    @Override
                                    public void onDeviceConnectFail() {
                                        MessageBox.show(activity,"设备连接失败");
                                    }
                                });
                            }
                        });
                    }
                    dialog.dismiss();
                }
            });
            return;
        }
        List<SiteEntity> siteList = UserDbController.getInstance(false).queryAll(SiteEntity.class);
        if (null == siteList || siteList.size() == 0) {
            v.showNoSiteDataDialog();
            return;
        }
        Intent intent = new Intent(activity, ExamDjActivity.class);
        intent.putExtra(SendParamConstant.EXAM_MODEL, examModel);
        activity.startActivity(intent);
    }

    @Override
    public void showPopWindowSatellites(TextView v) {
        View inflate = LayoutInflater.from(activity).inflate(R.layout.pop_satellites_number, null);
        TextView tvSatellite = inflate.findViewById(R.id.tv_satellite);
        GpsInfoBean gps = GpsInfoBean.getInstance();
        tvSatellite.setText("前天线: " + gps.getStatusDirection() + "/" + gps.getSatelliteFront() +
                "\u3000后天线: " + gps.getStatusPosition() + "/" + gps.getSatelliteBack());
        PopupWindow popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(inflate);
        taskGpsHandle.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvSatellite.setText("前天线: " + gps.getStatusDirection() + "/" + gps.getSatelliteFront() +
                        "\u3000后天线: " + gps.getStatusPosition() + "/" + gps.getSatelliteBack());
                if (popupWindow.isShowing()) {
                    taskGpsHandle.postDelayed(this, 1000);
                }
            }
        }, 1000);
        //点击非PopupWindow区域，PopupWindow会消失的
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(() -> taskGpsHandle.removeCallbacksAndMessages(null));
//        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.GRAY));    //要为popWindow设置一个背景才有效
        int width = v.getWidth();
        popupWindow.showAsDropDown(v, -width * 2 / 3, 0);
    }

    @Override
    public void getDeviceRiskResult() {
        riskControlModel.getCoachRiskResult(null);
    }

    @Override
    public void getCoachLoginQrCode(MainContract.View v) {
        LoadDialog.show(activity, "正在获取登录二维码");
        mainModel.getCoachLoginQrCode(new CommonCallBack() {
            @Override
            public void success(Object result) {
                LoadDialog.dismiss(activity);
                LoginQrcodeBean coachQrCodeBean = (LoginQrcodeBean) result;
                v.setCoachLoginQrCode(coachQrCodeBean);
            }

            @Override
            public void fail(String error) {
                MessageBox.show(activity, error);
            }
        });
    }

    @Override
    public void checkCoachSweepCode(String code, MainContract.View view) {
        mainModel.checkCoachSweepCode(code, new CommonCallBack() {
            @Override
            public void success(Object result) {
                getUserInfo(view);
            }

            @Override
            public void fail(String error) {
                view.coachLoginFail(error);
            }

            @Override
            public void complete() {
                new Handler().postDelayed(() -> view.checkCoachSweepCode(), 1000);
            }
        });
    }

    @Override
    public void accountLogin(String phone, String password, MainContract.View view) {
        if (StringUtils.isEmpty(phone)) {
            MessageBox.show(activity, "请输入账号");
            return;
        }
        if (StringUtils.isEmpty(password)) {
            MessageBox.show(activity, "请输入密码");
            return;
        }
        if (password.length() < 6) {
            MessageBox.show(activity, "密码错误");
            return;
        }
        mainModel.postMapLogin(phone, password, new CommonCallBack() {
            @Override
            public void success(Object result) {
                getUserInfo(view);
            }

            @Override
            public void fail(String error) {
                view.coachLoginFail(error);
            }
        });
    }

    private void getUserInfo(MainContract.View view) {
        mainModel.getUserInfo(new CommonCallBack() {
            @Override
            public void success(Object result) {
                UserConfigBean userConfigBean = (UserConfigBean) result;
                mainModel.saveUserInfo2Local(userConfigBean);
                view.getUserInfoSuccess();
                mainModel.checkUserDb();
                //获取用户风控信息
                riskControlModel.cancelRiskTimer();
                riskControlModel.startRiskCountTime(new CommonCallBack() {
                    @Override
                    public void complete() {
                        LoadDialog.dismiss(activity);
                        view.coachLoginComplete();
                    }
                });
            }

            @Override
            public void fail(String error) {
                mainModel.clearUserInfo();
                LoadDialog.dismiss(activity);
                MessageBox.show(activity, error);
                view.coachLoginComplete();
            }
        });
    }

    @Override
    public void removeAllCallBack() {
        taskGpsHandle.removeCallbacksAndMessages(null);
        riskControlModel.cancelRiskTimer();
    }

    @Override
    public boolean verifyUserDb() {
        return mainModel.checkUserDb();
    }

}
